package club.janna.jrpc.remoting.netty;

import club.janna.jrpc.remoting.Codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;

/**
 * @author Panbo.Guo
 */
public class NettyCodec extends ChannelDuplexHandler {

    private Codec codec;

    public NettyCodec(Codec codec) {
        this.codec = codec;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        // 读取数据到字节数组
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        byteBuf.release();
        // 解码
        Object obj = codec.decode(bytes);
        // 传递到下一个handler
        ctx.fireChannelRead(obj);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        ctx.write(codec.encode(msg));
    }
}
